<template>
  <div class="app-container calendar-list-container">
      <div class="filter-container">
                  <el-select clearable filterable @focus="customerNameFocus" v-model="listQuery.manpowerBaselineCustomerName"  style="width: 150px;margin-right:15px;margin-top:7px" placeholder="请选择客户名称">
                    <el-option
                    v-for="(item,index) in customerList"
                    :key="index"
                    :label="item.attributeMaintenanceCustomerName"
                    :value="item.attributeMaintenanceCustomerName">
                  </el-option>
                </el-select>
                <el-select clearable filterable @focus="customerNameFocus" v-model="listQuery.manpowerBaselineProductType" style="width: 150px;margin-right:15px;margin-top:7px" placeholder="请选择产品类型">
                    <el-option
                    v-for="(item,index) in customerList"
                    :key="index"
                    :label="item.attributeMaintenanceProductType"
                    :value="item.attributeMaintenanceProductType">
                  </el-option>
                </el-select>
          <el-select clearable filterable @focus="businessFocus" v-model="listQuery.manpowerBaselineDepartment" placeholder="请选择部门" style="width:150px;margin-right:15px;">
                    <el-option
                    v-for="(item,index) in personnelList" 
                    :key="index"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getData">搜索</el-button>
          <el-button v-if="userInfo.roleId == 29 || userInfo.roleId == 14 || userInfo.roleId == 12" class="filter-item" type="success" icon="el-icon-plus" @click="addShow('新增')">新增</el-button>
      </div>

      <!-- 表单 -->
      <el-table :data="dealList" v-loading="listLoading" element-loading-text="拼命加载中"  stripe border fit highlight-current-row style="width: 100%">
        <el-table-column label="序号" type="index" align="center" width="80px">
         <template slot-scope="scope">
          {{ (listQuery.page - 1) * listQuery.limit + scope.$index + 1 }}
         </template>
        </el-table-column>
          <el-table-column  label="客户名称" prop="manpowerBaselineCustomerName" align="center"/>
          <el-table-column  label="产品类型" prop="manpowerBaselineProductType" align="center"/>
          <el-table-column  label="部门" prop="manpowerBaselineDepartment" align="center"/>
          <el-table-column  label="产值大于等于（万元）" prop="manpowerBaselineProductionValue1" align="center"/>
          <el-table-column  label="产值小于（万元）" prop="manpowerBaselineProductionValue2" align="center"/>
          <el-table-column  label="所需人数" prop="manpowerBaselineNumberRequired" align="center"/>
          <el-table-column  label="修改人员" prop="manpowerBaselineUpdateUserName" align="center"/>
          <el-table-column  label="修改时间" prop="manpowerBaselineUpdateTime" align="center"/>
          <!-- 对oneNET进行修改与删除 -->
          <el-table-column  label="操作" align="center" width="230">
          <template slot-scope="scope" >
              <el-button v-if="userInfo.roleId == 29 || userInfo.roleId == 14 || userInfo.roleId == 12" size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button v-if="userInfo.roleId == 14" size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
          </template>
          </el-table-column>
      </el-table>

         <!-- pagination 分页 -->
      <div class="pagination-container">
          <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[5,10, 20, 30, 40,100,300,500]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          ></el-pagination>
      </div>
      
           <!-- <el-divider></el-divider> -->
           <el-upload
          style="margin-right: 20px;"
          class="upload-demo"
          ref="upload"
          :action="action"
          :on-success="handleSuccess"
          :file-list="fileList"
          :headers="httpHeader"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        </el-upload>

      <el-button style="margin-top: 10px;" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

      <!-- 修改工段信息弹出表单 -->
      <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px" @close="closeReset">
          <el-form :model="modifyform" :rules="rules" ref="formName">
              <el-form-item prop="manpowerBaselineCustomerName" label="客户名称" :label-width="formLabelWidth">
                  <el-select :disabled="title === '修改'" filterable @focus="customerNameFocus" @change="customerNameChange" v-model="modifyform.manpowerBaselineCustomerName"  style="width:400px" placeholder="请选择">
                    <el-option
                    v-for="(item,index) in customerList"
                    :key="index"
                    :label="item.attributeMaintenanceCustomerName +'--'+ item.attributeMaintenanceProductType"
                    :value="item.attributeMaintenanceCustomerName +'-'+ item.attributeMaintenanceProductType">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="title === '修改'" prop="manpowerBaselineProductType" label="产品类型" :label-width="formLabelWidth">
                  <el-select :disabled="title === '修改'" filterable @focus="customerNameFocus" @change="customerTypeChange" v-model="modifyform.manpowerBaselineProductType"  style="width:400px" placeholder="请选择">
                    <el-option
                    v-for="(item,index) in customerList"
                    :key="index"
                    :label="item.attributeMaintenanceCustomerName +'--'+ item.attributeMaintenanceProductType"
                    :value="item.attributeMaintenanceProductType +'-'+ item.attributeMaintenanceProductType">
                  </el-option>
                </el-select>
              </el-form-item>
              <div style="display: flex;">
                <el-form-item prop="manpowerBaselineDepartment" label="对应部门" :label-width="formLabelWidth">
                  <el-select filterable @focus="businessFocus" v-model="modifyform.manpowerBaselineDepartment" placeholder="请选择" style="width:150px">
                    <el-option
                    v-for="(item,index) in personnelList"
                    :key="index"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="manpowerBaselineNumberRequired" label="所需人数" :label-width="formLabelWidth">
                  <el-input v-model.number="modifyform.manpowerBaselineNumberRequired" style="width:150px" />
              </el-form-item>
            </div>
            <div style="display: flex;">
              <el-form-item prop="manpowerBaselineProductionValue1" label="产值范围" :label-width="formLabelWidth">
                <el-input v-model.number="modifyform.manpowerBaselineProductionValue1" placeholder="产值大于等于" style="width:150px" />
              </el-form-item>
              <el-form-item prop="manpowerBaselineProductionValue2" label="至" label-width="40px">
                <el-input v-model.number="modifyform.manpowerBaselineProductionValue2" placeholder="产值小于" style="width:150px" />
              </el-form-item>
              <div style="margin: 5px;">万元</div>
            </div>
          </el-form>
          <div slot="footer" class="dialog-footer">
          <el-button @click="closeReset">取 消</el-button>
          <el-button type="primary" @click="modifyWorkSec">确 定</el-button>
          </div>
      </el-dialog>
  </div>
</template>

<script>
import { forecastingFind,forecastingSave,forecastingUpd,findGroupCustomerNameAndProductType,forecastingDel } from '../../api/planManagement.js'
import { getDepartList } from '../../api/user.js'
import {uploadURL} from '@/utils/baseURL'
import { getToken } from '@/utils/auth'
export default {
  name:'hr_Maintenance',
  data() {
      return {
        // 获取人员列表
        personnelList:'',
          listQuery: {
              page: 1,
              limit: 10,
              isDelete: 0
          },
          modifyform: {
            manpowerBaselineCustomerName:'',
            manpowerBaselineProductType:'',
            manpowerBaselineDepartment:'',
            manpowerBaselineProductionValue1:'',
            manpowerBaselineProductionValue2:'',
            manpowerBaselineNumberRequired:''
          },
          rules: {
            manpowerBaselineCustomerName: [
                { required: true, message: '请输入客户名称', trigger: 'blur' }  
              ],
            manpowerBaselineProductType: [
              { required: true, message: '请选择产品类型', trigger: 'blur' }
            ],
            manpowerBaselineDepartment: [
              { required: true, message: '请选择对应部门', trigger: 'blur' }
            ],
            manpowerBaselineProductionValue1: [
              { required: true, message: '请输入产值', trigger: 'blur' },
            ],
            manpowerBaselineProductionValue2: [
              { required: true, message: '请输入产值', trigger: 'blur' },
            ],
            manpowerBaselineNumberRequired: [
              { required: true, message: '请输入所需人数', trigger: 'blur' },
              // { type: 'number', message: '必须为数字'},
            ]
          },
          action: uploadURL + `/back/order-forecasting/OrderForecastingRljxExcel`,
          fileList: [],
          httpHeader: {
          'Authorization': ''
      },
          dealList: '',
          total: 0,
          listLoading: false,
          dialogFormVisible: false,
          formLabelWidth: '100px',
          userInfo: this.$store.state.user.userInfo,
          title: '新增',
          customerList:'',
          bool:''
      }
  },
  methods: {
    submitUpload() {
      console.log(document.cookie);
      // this.httpHeader.Authorization = this.dealCookie(document.cookie)  
      this.httpHeader.Authorization = getToken()
      this.$refs.upload.submit()
      },
      // cookies的处理函数
    dealCookie(value) {
        const cookieArr = value.split('=')
        console.log(cookieArr);
        // cookieArr[2]测试服使用
        return cookieArr[1]
    },
    // 上传成功
    handleSuccess(response){
      if(response.code == 1){
        this.$message.success(response.msg)
      } else {
        this.$message.error(response.msg)
      }
      this.handleFilter()
    },
    // 客户名称获得焦点
    async customerNameFocus(){
      const res = await findGroupCustomerNameAndProductType()
      console.log(res);
      // this.customerNameLs = res.data
      this.customerList = res.data
    },
    customerNameChange(e){
      this.customerList.forEach(item => {
        if(item.attributeMaintenanceCustomerName == e){
          this.modifyform.manpowerBaselineProductType = item.attributeMaintenanceProductType
          this.modifyform.manpowerBaselineCustomerName = item.attributeMaintenanceCustomerName
        }
      })
    },
    customerTypeChange(e){
    },
    // 重置表单
    closeReset(){
      this.modifyform = {
        manpowerBaselineCustomerName:'',
        manpowerBaselineProductType:'',
        manpowerBaselineDepartment:'',
        manpowerBaselineProductionValue1:'',
        manpowerBaselineProductionValue2:'',
        manpowerBaselineNumberRequired:''
      }
      this.bool = false
      this.$refs.formName.resetFields()
      this.dialogFormVisible = false
    },
    // 打开弹框
    addShow(title){
      this.title = title
      this.dialogFormVisible = true
    },
    // 搜索按钮定义的函数
    async handleFilter() {
      this.listLoading = true
      let query = Object.assign({},this.listQuery)
      const data = await forecastingFind(query)
      this.dealList = data.data.list
      this.total = data.data.count
      this.listLoading = false
    },
    async businessFocus(){
      if(!this.personnelList) {
        const res = await getDepartList()
        this.personnelList = res.data
      }
    },
  // 删除用户按钮,使用elementui的messageBox弹框组件
  handleDelete(index,row) {
    this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(async () => {
        let res = await forecastingDel({id: row.id,isDelete: 1})
        console.log(res)
        if(res.code == 1){
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.handleFilter()
        } else {
          this.$message({
            type: 'error',
            message: `${res.msg}`
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info', 
          message: '已取消删除'
        })
      })
  },
  // 将弹框修改后的工段信息传入后台，并且消息提示是否修改成功
    async modifyWorkSec() {
      await this.$refs.formName.validate()
      if(this.modifyform.manpowerBaselineProductionValue1 && this.modifyform.manpowerBaselineProductionValue2){
        if(Number(this.modifyform.manpowerBaselineProductionValue1) > Number(this.modifyform.manpowerBaselineProductionValue2)){
          return this.$message.error('产值范围不规范！')
        }
      }
      let query = Object.assign({},this.modifyform)
      const arr = query.manpowerBaselineCustomerName.split('-')
      query.manpowerBaselineCustomerName = arr[0]
      query.manpowerBaselineProductType = arr[1]
      let data = ''
      if(this.title === '新增'){
        data = await forecastingSave(query)
      } else if(this.title === '修改'){
        data = await forecastingUpd(query)
      }
      console.log(data);
      if(data.code == '1'){
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.dialogFormVisible = false
        this.handleFilter()
      } else {
        this.$message({
          message: `${data.msg}`,
          type: 'warning'
        })
      }
    },
    // 点击修改按钮，将table表的内容传入弹框内部的表单
    // item为一行的表单数据，为一个对象
    handleEdit(item) {
      this.title = '修改'
      this.modifyform = Object.assign({},item)
      this.dialogFormVisible = true
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.handleFilter()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.handleFilter()
    },
    // 导出excel
    async hExportExcel() {
        let query = Object.assign({},this.listQuery)
        query.page = 1
        query.limit = 10000
        console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
        console.log(query)
        // if(this.userInfo.departmentName == '喷涂车间') { query.isSpray = true }
        let arr = await forecastingFind(query)
        console.log(arr);
        arr.data.list.forEach(item => {
            delete item.id
            delete item.isDelete
            delete item.limit
            delete item.orderForecastingAggregateAmount
            delete item.page
            delete item.manpowerBaselineUpdateJobNumer
            delete item.manpowerBaselineCreateTime
        });
        const { header, data } = this.transformDat(arr.data.list)
        console.log(header,data);
          import('@/vendor/Export2Excel').then(excel => {
          // excel表示导入的模块对象
          console.log(excel)
          excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '人力基线excel', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
          })
        })
      },
      transformDat(res) {
          const mapInfo = {
            manpowerBaselineCustomerName: '客户名称',
            manpowerBaselineProductType: '产品类型',
            manpowerBaselineDepartment: '部门',
            manpowerBaselineProductionValue1: '产值大于等于（万元）',
            manpowerBaselineProductionValue2: '产值小于（万元）',
            manpowerBaselineNumberRequired: '所需人数',
            manpowerBaselineUpdateUserName: '修改人员',
            manpowerBaselineUpdateTime: '修改时间'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
    getData() {
      this.listQuery.page = 1
      this.listQuery.limit = 10
      this.handleFilter()
    },
  },
  // 在生命周期函数调用"搜索"按钮绑定的函数，显示已有的数据
  async mounted() {
        this.handleFilter()
   },
}
</script>

<style>

</style>